package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.CouponCode;
import com.flycent.hqhs.bean.MyConsigneeAddress;
import com.flycent.hqhs.bean.OrderDTO;
import com.flycent.hqhs.bean.OrderList;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.bean.PurchaseProduct;
import com.flycent.hqhs.bean.UserInfo;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.HorizontalListView;
import com.flycent.hqhs.util.ContextUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 
 * @author fbl
 *  提交订单
 */
@SuppressLint("HandlerLeak") 
public class SubmitOrderActivity extends BackableTitleBarActivity{
	@ViewInject(id = R.id.order_address_relat ,click = "butClick") RelativeLayout mAddressRelat;
	@ViewInject(id = R.id.order_new_address_relat ,click = "butClick") RelativeLayout mNewAddressRelat;
	@ViewInject(id = R.id.order_payment_relat ,click = "butClick") RelativeLayout mPaymentRelat;
	@ViewInject(id = R.id.order_delivery_relat ,click = "butClick") RelativeLayout mDeliveryRelat;
	@ViewInject(id = R.id.order_invoice_relat ,click = "butClick") RelativeLayout mInvoiceRelat;
	@ViewInject(id = R.id.order_coupon_relat ,click = "butClick") RelativeLayout mCouponRelat;
	@ViewInject(id = R.id.order_selete_delivery_lin ) LinearLayout mSeleteDeliveryLin;
	@ViewInject(id = R.id.order_price_text) TextView mOrderPriceText;
	@ViewInject(id = R.id.order_product_price_account) TextView mProductPriceText;
	@ViewInject(id = R.id.order_product_price_freight) TextView mProductPriceFreightText;
	@ViewInject(id = R.id.order_submit_but,click = "butClick") Button mOrderSubmitBut;
	@ViewInject(id = R.id.order_username) TextView mOrderUserNameTxt;
	@ViewInject(id = R.id.order_tele_num) TextView mOrderTelNumTxt;
	@ViewInject(id = R.id.order_address_text) TextView mOrderAddressTxt;
	@ViewInject(id = R.id.order_payment_method) TextView mOrderPayMethodTxt;
	@ViewInject(id = R.id.order_delivery_method) TextView mDistributionMethodTxt;
	@ViewInject(id = R.id.order_invoice_method) TextView mInvoiceMethod;
	@ViewInject(id = R.id.order_coupon_text2) TextView mCouponNumberText; //优惠劵个数
	@ViewInject(id = R.id.order_coupon_text3) TextView mCouponUsedText;   //优惠劵是否使用
	@ViewInject(id = R.id.order_balance_text2) TextView mBalanceText;  //余额
	@ViewInject(id = R.id.order_switch_img,click = "butClick") ImageView mBalanceSwitchImg;  //是否使用余额
	@ViewInject(id = R.id.single_product_relat,click = "butClick") RelativeLayout mSingleRelat; //单个商品显示
	@ViewInject(id = R.id.single_product_img) ImageView mSingleImage;
	@ViewInject(id = R.id.single_product_name) TextView mSingleName;
	@ViewInject(id = R.id.single_product_price) TextView mSinglePrice;
	@ViewInject(id = R.id.single_product_number) TextView mSingleNumber;
	@ViewInject(id = R.id.double_product_relat,click = "butClick") RelativeLayout mDoubleRelat;
	@ViewInject(id = R.id.duble_product_number_text) TextView mDoubleNumber;
	@ViewInject(id = R.id.double_product_list)HorizontalListView mHorListView;

	//从上个activity获取的商品详情
	private String price;
	private String from = "";
	private long skuId ;
	private int weight,num;
	private String promotionType; //优惠type


	private MyConsigneeAddress mAddress;
	private List<MyConsigneeAddress> mConsigneeAddresses;
	private long mAddressId ; 
	private String mPayMethodId = "6";
	private int mCkeckDistributionId = 0;
	//配送名
	private String mDistributionName;
	//选择的快递的Id (低于100的才会有)
	private String mDistributionId = "";
	private float freight = 0; // 运费
	//发票
	private boolean isInvoice = true;
	private String invoiceTitle = "个人";

	//购物车传过来的token
	private String cartToken;
	//用户信息
	private UserInfo mUserInfo;
	private boolean isbalance = true; //是否使用余额

	//
	private OrderList mOrderList;

	//
	private OrderDTO mOrderDTO;
	//是否是购物车提交
	private boolean iscart = false;
	// 可用优惠劵
	private List<CouponCode> mCouponCodes;
	private String mCode = "";
	private String couponType = "";
	private float subPrice = 0 ;
	//
	private FinalDb db;
	//
	private List<PurchaseProduct> mPurchaseProducts;
	private OrderManagerActivity.OrderHorizonAdapter mAdapter;

	private Handler mHandler = new MyHandler(this);


	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_submit_order);
		FinalActivity.initInjectedView(this);
		getTitleBar().setTitle(R.string.title_submit_order);

		db = ((App) getApplication()).finalDb; 

		from = getIntent().getStringExtra("from");
		
		/** 判断是直接从商品详情页进来还是从购物车中进来 */
		if("ProductDetailActivity".equals(from)){  // 从商品页进来 
			skuId = getIntent().getLongExtra("skuId", 0);
			num = getIntent().getIntExtra("num", 0);
			promotionType = getIntent().getStringExtra("promotionType");
			iscart = false;

		}else {
			cartToken = getIntent().getStringExtra("token");
			iscart = true;
		}

		getProductList(); //获取商品列表
		getMyAddress(); //获取地址
		getUserInfo();  //获取用户信息 
		getCanUserCoupon(); //获取可用优惠劵
		weight = getIntent().getIntExtra("weight", 0);
		price = getIntent().getStringExtra("price");
		mProductPriceText.setText("￥"+price);
		mProductPriceFreightText.setText("￥"+freight);
		mOrderPriceText.setText("￥"+(Float.parseFloat(price)+freight));

		if(isbalance){
			mBalanceSwitchImg.setImageResource(R.drawable.icon_coupon_check);
		}else {
			mBalanceSwitchImg.setImageResource(R.drawable.icon_coupon_uncheck);
		}

		if(Float.parseFloat(price) >= 100 ){
			mDistributionMethodTxt.setText("商家包邮");
			//			mSeleteDeliveryLin.setVisibility(View.GONE);
		}else {
			mDistributionMethodTxt.setText("请选择快递");
		}


	}

	private void getProductList() {
		mPurchaseProducts = db.findAll(PurchaseProduct.class);
		if( mPurchaseProducts.size() == 1){
			PurchaseProduct mPurProduct = mPurchaseProducts.get(0);
			mSingleRelat.setVisibility(View.VISIBLE);
			mDoubleRelat.setVisibility(View.GONE);
			ImageLoader.getInstance().displayImage(mPurProduct.getImage(),mSingleImage);
			mSingleName.setText(mPurProduct.getName());
			mSingleNumber.setText("数量x"+mPurProduct.getQuantity());
			mSinglePrice.setText("￥"+mPurProduct.getPrice());

		}else {
			mSingleRelat.setVisibility(View.GONE);
			mDoubleRelat.setVisibility(View.VISIBLE);
			int num = 0;
			List<String> imagePath = new ArrayList<String>(); 
			for (int i = 0; i < mPurchaseProducts.size(); i++) {
				num = num+mPurchaseProducts.get(i).getQuantity();
				imagePath.add(mPurchaseProducts.get(i).getImage());
			}
			mDoubleNumber.setText("共"+num+"件商品");

			mAdapter =  new OrderManagerActivity.OrderHorizonAdapter(SubmitOrderActivity.this,  R.layout.item_order_manager_double_image);

			mHorListView.setAdapter(mAdapter);
			mAdapter.update(imagePath);

		}


	}

	private void getCanUserCoupon() {
		new Thread(){
			public void run() {
				try {
					mCouponCodes = WebClient.getInstance(SubmitOrderActivity.this).getCanUseCouponList(iscart, skuId+"", num+"");
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						mCouponCodes = null;
					else
						e.printStackTrace();
				}
				mHandler.sendEmptyMessage(4);
			};
		}.start();

	}
	//显示订单的价格
	private void setOrderPriceTextDate() {
		if( !isbalance ){
			mOrderPriceText.setText("￥"+(Float.parseFloat(price)+freight-subPrice));
		}else {
			if(mUserInfo.getBalance() == 0 ){
				mOrderPriceText.setText("￥"+(Float.parseFloat(price)+freight-subPrice));
				return;
			}
			mOrderPriceText.setText("￥"+((mUserInfo.getBalance()>=(Float.parseFloat(price)+freight)-subPrice) ? 0:((Float.parseFloat(price)+freight-subPrice)-mUserInfo.getBalance())));
		}
	}

	private void getUserInfo() {
		new Thread(){
			public void run() {
				try {
					mUserInfo = WebClient.getInstance(SubmitOrderActivity.this).getinfo();
					mHandler.sendEmptyMessage(2);
				} catch (WebException e) {
					e.printStackTrace();
				}
			};
		}.start();


	}

	/** 选择地址 */
	private void getMyAddress() {
		showLoadingDialog("");
		new Thread(){
			public void run() {
				try {
					PageEntity<MyConsigneeAddress> entry = WebClient.getInstance(SubmitOrderActivity.this).receiver(1, 10, "createDate", "desc");
					mConsigneeAddresses = entry.getContent();
					//没有默认没有选择是选第一个
					mAddress = mConsigneeAddresses.get(0);
					//没有点击有默认的情况的下选默认的
					for (int i = 0; i < mConsigneeAddresses.size(); i++) {
						if( mConsigneeAddresses.get(i).getIsDefault() ){
							mAddress = mConsigneeAddresses.get(i);
						}
					}
					//点击选择后选择选的
					for (int i = 0; i < mConsigneeAddresses.size(); i++) {

						if( mConsigneeAddresses.get(i).getId() == mAddressId){
							mAddress = mConsigneeAddresses.get(i);
						}
					}

				} catch (WebException e) {
					dismissLoadingDialog();
					if (e.getStatusCode() == WebException.TYPE_SERVER_RETURN_NULL){
						mConsigneeAddresses = null;
					}else if("shop.common.unauthorized".equals(e.getStatusCode())){
						ContextUtil.startActivity(SubmitOrderActivity.this, LoginActivity.class);
						SubmitOrderActivity.this.finish();
					}else{
						e.printStackTrace();
					}
				}
				mHandler.sendEmptyMessage(0);
			};

		}.start();


	}

	private  class MyHandler extends Handler{

		private final WeakReference<Activity> mActivity;

		public MyHandler(Activity activity) {  
			mActivity = new WeakReference<Activity>(activity);  
		}  
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);

			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					if( mConsigneeAddresses == null ){
						//还没有地址的时候
						mAddressRelat.setVisibility(View.GONE);
						mNewAddressRelat.setVisibility(View.VISIBLE);
					}else {
						mAddressRelat.setVisibility(View.VISIBLE);
						mNewAddressRelat.setVisibility(View.GONE);
						mAddressId = mAddress.getId();  //收货地址id
						mOrderUserNameTxt.setText(mAddress.getConsignee());
						mOrderTelNumTxt.setText(mAddress.getPhone());
						mOrderAddressTxt.setText(mAddress.getAreaName()+mAddress.getAddress());
						dismissLoadingDialog();
					}

					break;
				case 2:
					mBalanceText.setText("￥"+mUserInfo.getBalance());
					setOrderPriceTextDate();
					break;

				case 3:
					togetPayment();

					break;
				case 4:
					if(mCouponCodes == null ){
						mCouponNumberText.setText("0张可用");	
					}else {
						mCouponNumberText.setText(mCouponCodes.size()+"张可用");		
					}
					break;

				case 5:
					dismissLoadingDialog();

					Intent intent = new Intent(SubmitOrderActivity.this,SubmitOrderSuccessActivity.class);
					intent.putExtra("sn", mOrderList.getSn());
					intent.putExtra("orderStatus", mOrderList.getOrderStatus()+"");
					intent.putExtra("orderPrice", mOrderList.getPrice()+mOrderList.getFreight());
					startActivity(intent);
					finish();
					break;

				default:
					break;
				}
			}

		}

	}



	private void togetPayment() {
		new Thread(){
			public void run() {
				try {
					mOrderDTO = WebClient.getInstance(SubmitOrderActivity.this).doGetPayment(mOrderList.getSn()+"");
					mOrderList = mOrderDTO.getOrderDTO();
					mHandler.sendEmptyMessage(5);
				} catch (WebException e) {
					e.printStackTrace();
				}
			};
		}.start();


	};

	public void butClick(View v){
		// 商品清单
		if( v == mSingleRelat || v == mDoubleRelat){
			ContextUtil.startActivity(this, SubmitOrderListActivity.class);
		}

		//优惠劵
		if(v == mCouponRelat ){
			if( mCouponCodes == null){
				App.showShortToast("没有可用的优惠劵");
				return;
			}

			Intent intent = new Intent(this,ChoiceCouponActivity.class);
			intent.putExtra("mCode", mCode);
			intent.putExtra("iscart", iscart);
			intent.putExtra("skuId", skuId);
			intent.putExtra("num", num);
			startActivityForResult(intent,500);

		}

		//是否使用余额
		if(v == mBalanceSwitchImg){
			if( isbalance){
				mOrderPriceText.setText("￥"+(Float.parseFloat(price)+freight-subPrice));
				isbalance = false;
				mBalanceSwitchImg.setImageResource(R.drawable.icon_coupon_uncheck);
			}else {
				mOrderPriceText.setText("￥"+((mUserInfo.getBalance()>=(Float.parseFloat(price)+freight-subPrice)) ? 0:((Float.parseFloat(price)+freight-subPrice)-mUserInfo.getBalance())));
				isbalance = true;
				mBalanceSwitchImg.setImageResource(R.drawable.icon_coupon_check);
			}
		}

		//到选择地址的界面 
		if( v ==  mAddressRelat ){
			Intent intent = new Intent(SubmitOrderActivity.this,ChoiceAddressActivity.class);
			intent.putExtra("AddressId", mAddressId);
			startActivityForResult(intent, 100);

		}
		//新建地址
		if( v ==  mNewAddressRelat ){
			Intent intent = new Intent(SubmitOrderActivity.this,NewAddressActivity.class);
			intent.putExtra("from", "SubmitOrderActivity");
			intent.putExtra("inputType", "add");
			startActivityForResult(intent, 100);
		}
		//支付方式
		if( v == mPaymentRelat ){
			App.showShortToast("暂不支持第三方支付 ");

			//			Intent intent = new Intent(SubmitOrderActivity.this,ChoicePayMethodActivity.class);
			//			intent.putExtra("PayMethodId", mPayMethodId);
			//			startActivityForResult(intent, 200);
		}
		//发票
		if( v == mInvoiceRelat ){
			Intent intent = new Intent(SubmitOrderActivity.this,ChoiceInvoiceInformationActivity.class);
			intent.putExtra("isInvoice", isInvoice);
			intent.putExtra("invoiceTitle", invoiceTitle);
			startActivityForResult(intent,400);

		}
		// 选择快递类型
		if( v == mDeliveryRelat ){
			if(Float.parseFloat(price) >= 100 ){
				App.showShortToast("商家包邮，不需自己选择物流");
			}else {
				if( mAddressId == 0){
					App.showShortToast("请先选择地址");
					return;
				}
				Intent intent = new Intent(SubmitOrderActivity.this,ChoiceDistributionMethodActivity.class);
				intent.putExtra("checkId", mCkeckDistributionId);
				intent.putExtra("weight", weight);
				intent.putExtra("payPrice", price);
				intent.putExtra("areaId", mAddress.getArea().getId());
				startActivityForResult(intent, 300);
			}
		}
		//提交按钮
		if( v == mOrderSubmitBut ){
			if(Float.parseFloat(price) < 100  ){
				if("".equals(mDistributionId) ){
					App.showShortToast("请先选择配送方式");
					return;
				}
			}

			showLoadingDialog("");
			if("ProductDetailActivity".equals(from)){
				doBuyNow();
			}else {
				doBuyCart();
			}
		}
	}

	private void doBuyNow() {
		new Thread(){
			public void run() {
				try {
					mOrderList = WebClient.getInstance(SubmitOrderActivity.this).buyNow(skuId, num, mAddressId,"1",mDistributionId, mCode,isInvoice, invoiceTitle, isbalance,promotionType);
					mHandler.sendEmptyMessage(3);
				} catch (WebException e) {
					e.printStackTrace();
					dismissLoadingDialog();
				}
			};
		}.start();

	}

	private void doBuyCart() {
		new Thread(){
			public void run() {
				try {
					mOrderList = WebClient.getInstance(SubmitOrderActivity.this).buyCart(cartToken ,mAddressId,"1",mDistributionId, mCode,isInvoice, invoiceTitle, isbalance);
					mHandler.sendEmptyMessage(3);
				} catch (WebException e) {
					e.printStackTrace();
					dismissLoadingDialog();
				}
			};
		}.start();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if(data != null ){
			//优惠劵
			if(500 == resultCode ){
				if("".equals(data.getExtras().getString("mCode"))){
					mCode = "";
					couponType = "";
					subPrice = 0;
					mCouponUsedText.setText("未使用");
				}else {
					mCode = data.getExtras().getString("mCode");
					couponType = data.getExtras().getString("couponType");
					if("fullreduction".equals(couponType) ){
						subPrice = data.getExtras().getFloat("subPrice");
						App.showLog("order-subPrice=="+subPrice);
					}
					mCouponUsedText.setText("已使用");
				}
				setOrderPriceTextDate();
				
			}

			//地址选择
			if(100 == resultCode ){
				mAddressId = data.getExtras().getLong("mid");
				getMyAddress();
			}
			//支付方式
			if(200 == resultCode ){
				mPayMethodId = data.getExtras().getString("mPayId");
				setPayMethodText();
			}
			//配送方式
			if(300 == resultCode ){
				mCkeckDistributionId = data.getIntExtra("checkId", 0);
				mDistributionName = data.getExtras().getString("mDistributionName");
				mDistributionId = data.getExtras().getString("mDistributionID");
				freight = data.getFloatExtra("mDistributionPrice", 0);
				mDistributionMethodTxt.setText(mDistributionName);
				mProductPriceFreightText.setText("￥"+freight);
				setOrderPriceTextDate();
			}
			//发票类型
			if( 400 == requestCode ){
				isInvoice = data.getBooleanExtra("isInvoice", true);
				invoiceTitle = data.getStringExtra("invoiceTitle");
				setInvoiceMethodText();
			}
		}else {
			if( requestCode == 100 ){
				getMyAddress();
			}
		}
	}


	private void setPayMethodText() {
		if("6".equals(mPayMethodId)){
			mOrderPayMethodTxt.setText("银联支付");
		}else if("2".equals(mPayMethodId)){
			mOrderPayMethodTxt.setText("支付宝");	
		}
	}

	private void setInvoiceMethodText(){
		if( isInvoice){
			mInvoiceMethod.setText("普通发票");
		}else {
			mInvoiceMethod.setText("不开发票");
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}

}
